//
//  NewNetWorkManager.m
//  VLv
//
//  Created by lanouhn on 16/6/27.
//  Copyright © 2016年 Leo. All rights reserved.
//

#import "NewNetWorkManager.h"
#import "AFNetworking.h"

@implementation NewNetWorkManager

/*方法的作用:GET 请求
 *@param urlStr : 数据请求接口地址
 *@param dic : 接口请求数据参数
 *@param finish : 数据请求失败的回调
 *@param conError : 数据请求失败的回调
 */
+ (void)requestGETWithURLString:(NSString *)urlStr parDic:(NSDictionary *)dic finish:(void(^)(id responseObject))finish conError:(void(^)(NSError *error))conError {
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置请求超时
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 3.0;//设置请求超时时间
    
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    //支持 text/html 文件格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", nil];
    
    //加上这行代码, https ssl 验证
   // [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    [manager GET:urlStr parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        //请求数据的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable response) {
        //数据请求完成的回调
        finish(response);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //数据请求完成的回调

        conError(error);
    }];
}


/*方法的作用:POST 请求
 *@param urlStr : 数据请求接口地址
 *@param dic : 接口请求数据参数
 *@param finish : 数据请求失败的回调
 *@param conError : 数据请求失败的回调
 */
+ (void)requestPOSTWithURLString:(NSString *)urlStr parDic:(NSDictionary *)dic finish:(void(^)(id responseObject))finish conError:(void(^)(NSError *error))conError {
    
    [QMUITips showLoadingInView:[[UIApplication sharedApplication] keyWindow]];

    [NewNetWorkManager monitorNetwork];

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置请求超时
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 3.0;//设置请求超时时间
    
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    //添加HTTPHeader
   // [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content－Type"];
    
        //支持 text/html 文件格式
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain",@"text/javascript",@"text/xml",  nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //加上这行代码, https ssl 验证
    //[manager setSecurityPolicy:[self customSecurityPolicy]];
    
    [manager POST:urlStr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //请求参数
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //请求数据的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [QMUITips hideAllToastInView:[[UIApplication sharedApplication] keyWindow] animated:YES];

        //数据请求完成的回调
        finish(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //数据请求完成的回调
        [QMUITips hideAllToastInView:[[UIApplication sharedApplication] keyWindow] animated:YES];

        conError(error);
        
        
        
    }];
    
}


+ (void)uploadHeaderWithUrl:(NSString *)urlStr parDic:(NSDictionary *)dic  imageData:(NSData *)data fileName:(NSString *)fielName finish:(void(^)(id responseObject))finish conError:(void(^)(id responseObject))failure{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置请求超时
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 3.0;//设置请求超时时间
    
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    //添加HTTPHeader
    // [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content－Type"];
    
    //支持 text/html 文件格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",  nil];
    
    //加上这行代码, https ssl 验证
    [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    [manager POST:urlStr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //请求参数
        
        //avatar 特定标识符 后台协定
        [formData appendPartWithFileData:data name:@"avatar" fileName:fielName mimeType:@"image/jpeg"];
        
        
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //请求数据的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //数据请求完成的回调
        
        if ([responseObject[@"result_code"] isEqualToString:@"0x00000000"]) {
            finish(@{@"msg":@"更换成功",@"picture":responseObject[@"data"][@"picture"]});
        }else{
            failure(@{@"msg":responseObject[@"msg"]});
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //数据请求完成的回调
        failure(@{@"msg":@"上传失败,请重新操作"});
    }];
}



+ (AFSecurityPolicy*)customSecurityPolicy {
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
 
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.pinnedCertificates = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    return securityPolicy;
}



+ (void)monitorNetwork{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变时调用
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
        }
    }];
    
    //开始监控
   // [manager startMonitoring];
 
}



@end
